package com.xdtech.web.handler;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.xdtech.web.util.ExceptionUtil;



/**
 * spring mvc异常捕获类
 * 
 */
//@Component
public class MyExceptionHandler implements HandlerExceptionResolver {

	private static final Logger logger = Logger
			.getLogger(MyExceptionHandler.class);

	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		String exceptionMessage = ExceptionUtil.getExceptionMessage(ex);
		logger.error(exceptionMessage);
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("exceptionMessage", exceptionMessage);
		model.put("ex", ex);
		return new ModelAndView("error/errorpage", model);
//		logger.error("异常日志拦截", ex);
//		String viewName = determineViewName(ex, request);
//		if (viewName != null) {// html格式返回
//
//			if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
//					.getHeader("X-Requested-With") != null && request
//					.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
//				// 如果不是异步请求
//
//				Integer statusCode = determineStatusCode(request, viewName);
//				if (statusCode != null) {
//					applyStatusCodeIfPossible(request, response, statusCode);
//				}
//				viewName="template/"+ configService.getConfigByKey("SYS_THEME")+"/"+viewName;
//				request.setAttribute("statusCode", statusCode);
//				request.setAttribute("exceptionMsg", getExceptionMsg(ex.getClass().getSimpleName(),request,ex.getMessage()));
//				return getModelAndView(viewName, ex, request);
//			} else {// JSON格式返回
//
//				try {
//					response.setContentType("text/html; charset=utf-8");
//					PrintWriter writer = response.getWriter();
//					writer.write(getExceptionMsg(ex.getClass().getSimpleName(),request,ex.getMessage()));//返回异常类型及其消息信息
//
//					writer.flush();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//				return null;
//			}
//		} else {
//			return null;
//		}
	}
	
//	private String getExceptionMsg(String className,HttpServletRequest request,String exMessageCode){
//		return getMsgByMsgKey(className, request,exMessageCode);
//	}
//	private String getMsgByMsgKey(String msgKey,HttpServletRequest request,String exMessageCode) {
//		RequestContext requestContext = new RequestContext(request);
//		return requestContext.getMessage(msgKey+"."+exMessageCode)+"["+exMessageCode+"]";
//	}
}
